#include "StdAfx.h"
#include "ServerClient.h"
#include "Server.h"
#include <WinSock2.h>
#include <string>

using namespace std;

ServerClient::ServerClient(string n, SOCKET* s, Server* se) {
	name = n;
	clientSocket = s;
	server = se;
}

ServerClient::~ServerClient(void) {
	delete clientSocket;
}

string ServerClient::getName() {
	return name;
}

void ServerClient::start() {
	CreateThread(0,0,run,this,0,NULL);
}

bool ServerClient::listen() {
	char* buffer = new char[256];
	int i = recv( *clientSocket, buffer, 256, 0 );
	if(i != -1) {
		buffer[i] = '\0';
		server->sendToAll(buffer);
		delete[] buffer;
		return true;
	}
	delete[] buffer;
	return false;
}

void ServerClient::Send(char * data) {
	send( *clientSocket, data, strlen( data ), 0 );
}

void ServerClient::disconnect() {
	server->disconnectUser(this);
}

unsigned long _stdcall ServerClient::run(void * param) {
	ServerClient* This = (ServerClient*)param;
	while(true) {
		bool b = This->listen();
		if(!b) {
			This->disconnect();
			break;
		}
	}
	return 0;
}
